package sicnu.cs.ich.activity.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Service;
import sicnu.cs.ich.activity.mapper.ActivityMapper;
import sicnu.cs.ich.activity.service.IActivityRankService;
import sicnu.cs.ich.api.common.Constants;
import sicnu.cs.ich.api.domain.entity.Activities;
import sicnu.cs.ich.common.services.impl.RedisService;
import sicnu.cs.ich.common.util.CollectionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 黎琦
 * @date 2021/12/23 15:48
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class ActivityRankServiceImpl implements IActivityRankService {
    private final DefaultMQProducer producer;
    private final RedisService redisService;
    private final ActivityMapper activityMapper;

    @Override
    public void activityHitIncrement(Integer id) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        var msg = new Message("activity","activity", JSON.toJSONBytes(id));
        producer.send(msg);
    }

    @Override
    public void callHitIncrement(Integer id) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        var msg = new Message("activity","call", JSON.toJSONBytes(id));
        producer.send(msg);
    }

    @Override
    public List<Activities> getActivityRanking() {
        var list = redisService.getList(Constants.REDIS_RANK_ACTIVITY_HIT, 0, -1);
        if(CollectionUtil.isEmpty(list)){
            //发送消息

        }
        List<Integer> ids = new ArrayList<>(list.size());
        for (Object o : list) {
            ids.add((Integer) o);
        }
        return activityMapper.selectByIds(ids);
    }
}
